//
//  WeatherCarouselView.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/5/10.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "WeatherCarouselView.h"
#import "WeatherView.h"
#import "UIView+Gradient.h"
@interface WeatherCarouselView()

@property (nonatomic, strong)WeatherView * hideView;
@property (nonatomic, strong)WeatherView * currentView;

@property (nonatomic) NSInteger i;
@end



@implementation WeatherCarouselView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        _currentView = [[WeatherView alloc] initWithFrame:CGRectMake(0,0, frame.size.width, frame.size.height)];
        [self addSubview:_currentView];
        _currentView.backgroundColor = [UIColor clearColor];
        
        _hideView = [[WeatherView alloc] initWithFrame:CGRectMake(0,frame.size.height, frame.size.width, 0)];
        [self addSubview:_hideView];

        [self initTimer];
    }
    return self;
}

- (void)initTimer {
    
    
    @weakify(self);
    [NSTimer scheduledTimerWithTimeInterval:4.0f block:^(NSTimer * _Nonnull timer) {
        
        @strongify(self);
        
        [self changeView];
        
    } repeats:YES];
}

- (void)setWeatherArray:(NSArray *)weatherArray {
    
    _weatherArray = weatherArray;
    [self changeView];
}

- (void)changeView {
    
    if (self.weatherArray.count == 0) {
        self.hidden = YES;
        return;
    }
    self.hidden = NO;
    
    NSInteger index = self.i % self.weatherArray.count;
    
    Weather *weather = self.weatherArray[index];
    
    Weather *nextWeather = (index + 1) >= self.weatherArray.count ? self.weatherArray[0] : self.weatherArray[index + 1];
    self.i ++;
    [self.currentView configWeather:weather];
    [self.hideView configWeather:nextWeather];
    
    

    @weakify(self);
    
    [UIView animateWithDuration:1 animations:^{
        @strongify(self);
        _hideView.frame = CGRectMake(0,0,self.frame.size.width, self.frame.size.height);
        _currentView.frame = CGRectMake(0,-self.frame.size.height,self.frame.size.width, self.frame.size.height );
        
    } completion:^(BOOL finished) {
        @strongify(self);
        _currentView.frame = CGRectMake(0,self.frame.size.height,self.frame.size.width , self.frame.size.height);
        WeatherView * view = _currentView;
        _currentView = _hideView;
        _hideView = view;
        
    }];
}

@end
